package io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.LinkedList;
import java.util.List;

public class BaseHouseReader implements HouseReader {

	private char[][] map;

	public BaseHouseReader(Reader reader) throws IOException {
		BufferedReader br = new BufferedReader(reader);
		String line = br.readLine();
		if (line == null)
			throw new IOException("No map defined!");
		List<String> lines = new LinkedList<String>();
		int lastWidth = -1;
		while (line != null) {
			if (lastWidth > 0 && line.length() != lastWidth)
				throw new IOException("Illegal world data!");
			lines.add(line);
			lastWidth = line.length();
			line = br.readLine();
		}
		br.close();

		map = new char[lines.size()][lastWidth];
		int i = 0;
		for (String l : lines) {
			for (int j = 0; j < l.length(); j++) {
				if (l.charAt(j) != PERSONA && l.charAt(j) != LAMPADINA
						&& l.charAt(j) != WALL && l.charAt(j) != PORTA
						&& l.charAt(j) != BLANK)
					throw new IOException("Illegal symbol \"" + l.charAt(j)
							+ "\"!");
				map[i][j] = l.charAt(j);
			}
			i++;
		}
	}

	public char get(int i, int j) {
		return map[i][j];
	}

	public int getWidth() {
		return map[0].length;
	}

	public int getHeight() {
		return map.length;
	}
}
